//******** 追光视界PHP转JS版(酷9 APP专用) - 优化版 ********//
// 频道地址格式：http://你的服务器地址/追光视界.js?id=cctv1

function main(item) {
    // 获取频道ID
    const url = item.url;
    const id = ku9.getQuery(url, "id") || "cctv1";
    
    // 频道ID映射表
    const CHANNEL_MAP = {
        'cctv1': 'G_CCTV-1-HQ', 'cctv2': 'G_CCTV-2-HQ', 'cctv3': 'G_CCTV-3-HQ', 
        'cctv4': 'G_CCTV-4-HQ', 'cctv5': 'G_CCTV-5-HQ', 'cctv5p': 'G_CCTV-5PLUS-HQ',
        'cctv6': 'G_CCTV-6-HQ', 'cctv7': 'G_CCTV-7-HQ', 'cctv8': 'G_CCTV-8-HQ',
        'cctv9': 'G_CCTV-9-HQ', 'cctv10': 'G_CCTV-10-HQ', 'cctv11': 'G_CCTV-11-HQ',
        'cctv12': 'G_CCTV-12-HQ', 'cctv13': 'G_CCTV-13-HQ', 'cctv14': 'G_CCTV-14-HQ',
        'cctv15': 'G_CCTV-15-HQ', 'cctv16': 'G_CCTV-16-HQ', 'cctv17': 'G_CCTV-17-HQ',
        'cgtnjl': 'G_CGTVJL-HD', 'cgtn': 'G_CCTV-NEWS', 'cgtna': 'G_CGTN_A',
        'cgtnp': 'G_CGTN-PYCCNN', 'cgtne': 'G_CGTN-ESPANOL', 'cgtnf': 'G_CGTN-FRANCAIS',
        'cctv4k': 'G_CCTV-4K-HD', 'bjws4k': 'G_BEIJING-4K', 'scws4k': 'G_SICHUAN-4K',
        'sdws4k': 'G_SHANDONG-4K', 'dfws4k': 'G_DONGFANG-4K', 'hnws4k': 'G_HUNAN-4K',
        'jsws4k': 'G_JIANGSU-4K', 'szws4k': 'G_SHENZHEN-4K', 'gdws4k': 'G_GUANGDONG-4K',
        'zjws4k': 'G_ZHEJIANG-4K', 'gdws': 'G_GUANGDONG-HQ', 'jsws': 'G_JIANGSU-HQ',
        'zjws': 'G_ZHEJIANG-HQ', 'hunws': 'G_HUNAN-HQ', 'dfws': 'G_DONGFANG-HQ',
        'bjws': 'G_BEIJING-HQ', 'szws': 'G_SHENZHEN-HQ', 'lnws': 'G_LIAONING-HQ',
        'ahws': 'G_ANHUI-HQ', 'sdws': 'G_SHANDONG-HQ', 'hljws': 'G_HEILONGJIANG-HQ',
        'tjws': 'G_TIANJIN-HQ', 'gxws': 'G_GUANGXI-HQ', 'dnws': 'G_DONGNAN-HQ',
        'gsws': 'G_GANSU-HQ', 'gzws': 'G_GUIZHOU-HQ', 'hainws': 'G_HAINAN-HQ',
        'hebws': 'G_HEBEI-HQ', 'henws': 'G_HENAN-HQ', 'hubws': 'G_HUBEI-HQ',
        'jlws': 'G_JILIN-HQ', 'jxws': 'G_JIANGXI-HQ', 'kbws': 'G_KANGBA',
        'adws': 'G_ANDUO', 'btws': 'G_BINGTUAN', 'nmgws': 'G_NEIMENGGU',
        'nxws': 'G_NINGXIA', 'nlws': 'G_NONGLIN', 'qhws': 'G_QINGHAI',
        'ssws': 'G_SANSHA-HQ', 'shanxws': 'G_SHANXI-HQ', 'scws': 'G_SICHUAN-HQ',
        'xzws': 'G_XIZANG', 'xjws': 'G_XINJIANG', 'ybws': 'G_YANBIAN',
        'ynws': 'G_YUNNAN-HQ', 'cqws': 'G_CHONGQING-HQ', 'xmws': 'G_XIAMEN',
        'sdjy': 'G_SDETV', 'bjadjs': 'G_BEIJINGJS-HD', 'jtlc': 'G_JIATINGLC',
        'jykt': 'G_JINYING', 'kkse': 'G_KAKU', 'nxss': 'G_NVXINGSS',
        'tywq': 'G_TIANYUANWQ', 'xdkt': 'G_XUANDONG', 'ymkt': 'G_YOUMAN',
        'gxpd': 'G_GUOXUE', 'lgs': 'G_LAOGUSHI', 'cetv1': 'G_CETV-1-HQ',
        'cetv2': 'G_CETV-2', 'cetv3': 'G_CETV-3', 'cetv4': 'G_CETV-4',
        'hb1': 'GITV-HB-1', 'hb2': 'GITV-HB-2', 'hb3': 'GITV-HB-3',
        'hb4': 'GITV-HB-4', 'hb5': 'GITV-HB-5', 'hb6': 'GITV-HB-6',
        'yggw': 'G_YANGGUANGGOU', 'hxgw': 'G_HAOXIANG', 'yxhw': 'GITV-GG-1',
        'mhshj': 'GITV-GG-2', 'ai1': 'GITV-AI-1', 'ai14k': 'GITV-AI-4K',
        'zy1': 'GITV-ZY-1', 'zy2': 'GITV-ZY-2', 'zy3': 'GITV-ZY-3',
        'zy4': 'GITV-ZY-4', 'zy5': 'GITV-ZY-5', 'zy6': 'GITV-ZY-6',
        'zy7': 'GITV-ZY-7', 'zy8': 'GITV-ZY-8', 'zy9': 'GITV-ZY-9',
        'zy10': 'GITV-ZY-10'
    };
    
    // 获取实际频道ID
    const channelId = CHANNEL_MAP[id] || CHANNEL_MAP['cctv1'];
    
    // 检查缓存
    const cacheKey = "zgsj_" + channelId;
    const cachedUrl = ku9.getCache(cacheKey);
    if (cachedUrl && cachedUrl !== "null" && cachedUrl !== "") {
        return JSON.stringify({ 
            url: cachedUrl,
            headers: {
                'User-Agent': 'okhttp/3.8.1',
                'Referer': 'http://hecmcc-gvp-zy.playauth.gitv.tv/'
            }
        });
    }
    
    // 基础播放URL - 直接可用的URL
    const baseUrl = "http://hegd-livod.ali-cdn.gitv.tv/gitv_live/" + channelId + "/" + channelId + ".m3u8";
    
    // 生成随机MAC地址
    function generateUpperMac(sep) {
        const parts = [];
        for (let i = 0; i < 6; i++) {
            const b = Math.floor(Math.random() * 256);
            parts.push(b.toString(16).padStart(2, '0').toUpperCase());
        }
        return parts.join(sep);
    }
    
    // 常量D
    function D() {
        return "fUw8mWqp0ih8KRPzmgHnoL4fx0X0N78o4Od6D4lFTV32S7uVa2mYSZjRofquHHU16gkpjvInD07bKwb05S0hlJYfYMmUyQprvoEqM2I8Dfe2oX0MTAJEg8DYDul6lJqg";
    }
    
    // 生成认证token
    function generateAuth(j, expire) {
        const strD = D();
        const maxIdx = strD.length - 19;
        const start = j % (maxIdx > 1 ? maxIdx : 1);
        const sub = strD.substring(start, start + 20);
        const toHash = sub + expire.toString();
        // 优先使用SHA256，如果不支持则使用MD5
        const hash = ku9.sha256 ? ku9.sha256(toHash) : ku9.md5(toHash);
        return hash + "_" + j + "_" + expire;
    }
    
    // 格式化时间戳
    function formatTimestamp(ts) {
        const date = new Date(ts * 1000);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        const seconds = date.getSeconds().toString().padStart(2, '0');
        return year + month + day + hours + minutes + seconds;
    }
    
    // 尝试获取认证播放URL
    function tryGetAuthUrl() {
        try {
            const mac = generateUpperMac(':');
            const timestamp = Math.floor(Date.now() / 1000);
            const playAuthToken = generateAuth(timestamp, 120);
            const gTime = formatTimestamp(timestamp);
            
            // 认证URL
            const authUrl = "http://hecmcc-gvp-zy.playauth.gitv.tv/itv/playauth?" +
                "playAuthToken=" + playAuthToken + "&gMac=" + mac +
                "&gTimestamp=" + gTime + "&gRequests=1&appVersion=1539&authenType=2&partnerCode=HB_CMCC_GVP_ZY&appType=gvp&gAreaId=CHN&gAppChannel=DEFAULT&gSoftTermId=SOFT_TERMINAL&gManufacturer=meizu&gModel=22_IP103H_2024&gStbId=unknown&gOsType=android&gOsVersion=9&gApiLevel=28&gAppVersionCode=1539&gAppVersionName=1.5.39&gDowngrade=NONEMERGENCY&gRomVersion=DEFAULT&gProductLineCode=GVP&gAndroidId=ac0dd0fdeab5c05b&gDeviceID=888e8bb9-3638-3512-89bb-3cd0e8f05fee";
            
            const payload = {
                'contentId': channelId,
                'playUrl': baseUrl + "?gMac=" + mac + "&partnerCode=HB_CMCC_GVP_ZY",
                'stbId': '00e8c940',
                'userId': 'yk1234'
            };
            
            const headers = {
                'User-Agent': 'okhttp/3.8.1',
                'Content-Type': 'application/json',
                'Host': 'hecmcc-gvp-zy.playauth.gitv.tv',
                'Connection': 'keep-alive'
            };
            
            // 尝试使用post方法
            const resp = ku9.post(authUrl, headers, JSON.stringify(payload));
            
            if (resp && resp !== '') {
                const data = JSON.parse(resp);
                if (data && data.data && data.data.playUrl) {
                    const authPlayUrl = data.data.playUrl;
                    // 缓存认证URL（2小时）
                    ku9.setCache(cacheKey, authPlayUrl, 2 * 60 * 60 * 1000);
                    return authPlayUrl;
                }
            }
        } catch (e) {
            // 认证失败，返回null使用基础URL
        }
        return null;
    }
    
    // 主逻辑
    let finalPlayUrl = baseUrl;
    
    // 尝试获取认证URL，如果失败则使用基础URL
    const authUrl = tryGetAuthUrl();
    if (authUrl) {
        finalPlayUrl = authUrl;
    }
    
    // 返回播放地址
    const result = {
        url: finalPlayUrl,
        headers: {
            'User-Agent': 'okhttp/3.8.1',
            'Referer': 'http://hecmcc-gvp-zy.playauth.gitv.tv/'
        }
    };
    
    return JSON.stringify(result);
}